import 'dart:convert' as convert;
import 'dart:core';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/global_common.dart';
import 'package:flutter_syt/global_easy_loading.dart';
import 'package:flutter_syt/routes.all.dart';

// import 'package:flutter_webview_pro/webview_flutter.dart';
import 'package:intl/intl.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/domain/widgets/photo_views_more_screen.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/fade_route.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:flutter_syt/widgets/loading_widget.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

class WebProtocolDetailPage extends StatefulWidget {
  final String url;

  const WebProtocolDetailPage(this.url);

  @override
  State<StatefulWidget> createState() {
    return _WebProtocolDetailState();
  }
}

class _WebProtocolDetailState extends State<WebProtocolDetailPage>
    with RouteAware {
  bool isLoading = true;
  bool isGetTitle = false;
  String? error;
  late WebViewController _controller;

  @override
  void initState() {
    super.initState();
    // if (Platform.isAndroid) {
    // WebViewWidget.platform = SurfaceAndroidWebView();
    // }
    var url = widget.url;
    var storyLocal = appContext.storage.getString("storyLocal");
    if (storyLocal != null) {
      url =
          url + (url.contains('?') ? "&lang=$storyLocal" : "?lang=$storyLocal");
    } else {
      var local = Intl.getCurrentLocale();
      url = url + (url.contains('?') ? "&lang=$local" : "?lang=$local");
    }
    _controller = WebViewController();

    _controller.setUserAgent("wisdom Universiade");
    _controller.setJavaScriptMode(JavaScriptMode.unrestricted);
    _controller.setNavigationDelegate(NavigationDelegate(
      onPageFinished: (result) {
        print('web加载完了 $result');
        if (isLoading == true) {
          Future.delayed(Duration(milliseconds: 100), () async {
            _getTitle();
          });
        }
        if (mounted) {
          setState(() {
            // print('web加载完了 刷新State');
            isLoading = false;
          });
        }
      },
      onPageStarted: (result) async {
        print('web加载开始了 $result ');
        // var t = await _controller?.getTitle();
        // print('web加载完了 获取标题1   $t');
        // if (isLoading == null) {
        //   return;
        // }
        if (mounted) {
          setState(() {
            // print('web加载开始了 刷新State');
            // if (isGetTitle) {
            //   return;
            // }
            isLoading = true;
          });
        }
      },
      onWebResourceError: (webError) {
        // if (mounted) {
        //   setState(() {
        //     print('web加载完了 报错了 $webError');
        //     isLoading = false;
        //     error = S().network_error;
        //   });
        // }
      },
    ));
    _controller.addJavaScriptChannel('checkFullSize',
        onMessageReceived: (message) {
      var str = message.message.toString();

      if (str.isNotEmpty) {
        Map<String, dynamic> json = convert.jsonDecode(str);
        DLog(json);
        if (json.keys.contains('urls')) {
          List<String> lists = [];
          json['urls'].forEach((element) {
            lists.add(element.toString());
          });
          Navigator.of(context).push(
            FadeRoute(
                page: PhotoViewMoreScreen(
              imageRows: lists,
              defaultImage: int.parse('${json['default'] ?? 0}'),
            )),
          );
        }
      }
    });

    _controller.addJavaScriptChannel('nativeUserInfo',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeUserInfo ${message.message}');
      var str = message.message.toString();
      Map<String, dynamic> json = convert.jsonDecode(str);
      var uid = "${json["uid"]}";
      var result = '';
      if (UserInfo.me.isLogin) {
        result = '{"status":"1","message":"success","uid":"$uid",'
            '"data":{"nickname":"${UserInfo.me.nickname}","avatar":"${UserInfo.me.avatar}"}}';
      } else {
        result = '{"status":"0","message":"not login", "uid":"$uid"}';
      }
      _controller.runJavaScript("NATIVE2JS('${result}');");
    });
    _controller.addJavaScriptChannel('nativeLogin',
        onMessageReceived: (message) {
      DLog('addJavaScriptChannel  nativeLogin ${message.message}');
      var str = message.message.toString();
      Map<String, dynamic> json = convert.jsonDecode(str);
      var appid = "${json["app_id"]}";
      var authUrl = "${json["auth_url"]}";
      var uid = "${json["uid"]}";
      // http://221.237.109.31:8052
      // eb2f6530-1d38-11ee-8b5c-8570f30318ae
      // var isClean = "${json["is_clean_cache"]}";
      _userAuth(uid, appid, authUrl);
    });
    _controller.loadRequest(Uri.parse(url));
    DLog('dalsjd   ${url}');
  }

  void _userAuth(
      String uid,
      String appId,
      String authUrl,
      ) async {
    void doAuth() async {
      try {
        var json = await API.shared.bridge.authorize(
          appId,
          authUrl,
          // isClean
        );
        //
        var code = "${json["code"]}";
        var openid = "${json["openid"]}";
        var iscleancache = "${json["is_clean_cache"]}";
        var result = "";
        if (code != 'null') {
          result =
          '{"status":"1","message":"success","uid":"$uid","data":{"uid":"$uid","code":"$code","openid":"$openid","iscleancache":"$iscleancache"}}';
        } else {
          result = '{"status":"0","message":"code is null", "uid":"$uid"}';
        }
// _controller.runJavaScript(javaScript)
        _controller.runJavaScript("NATIVE2JS('$result');");
      } catch (e, stack) {
        var msg = S().network_error;
        if (e is DioError && !(e.error is SocketException)) {
          msg = e.message ?? '';
          // if (e.response?.statusCode != 401) {
          customShowError(msg);
          // }
        } else {
          customShowError(msg);
        }

        var failed = '{"status":"0","message":"$msg", "uid":"$uid"}';
        _controller.runJavaScript("NATIVE2JS('$failed');");
      }
    }

    if (UserInfo.me.isLogin) {
      doAuth();
    } else {
      GlobalData.loaginCallback = true;
      // widget.currentJson['uid'] = uid;
      // widget.currentJson['appId'] = appId;
      // widget.currentJson['authUrl'] = authUrl;
      GlobalData.pageFrom = "web_detail";
      RouteManager.push(context, RoutMapping.loginByPwd()).then((value) {
        if (UserInfo.me.isLogin != true) {
          // Navigator.pop(context);
        }
      });
    }
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _closePage() {
    print('close page');
    Navigator.pop(context);
  }

  void _back() async {
    var can = await _controller.canGoBack();
    if (can == true) {
      _controller.goBack();
    } else {
      _closePage();
    }
  }

  void _getTitle() async {
    isGetTitle = true;
    var t = await _controller.getTitle();
    // print(t);
    print('web加载完了 获取标题   $t');
    if (t != 'undefined') {
      if (mounted) {
        setState(() {
          _title = t ?? "";
        });
      }
    }
  }

  var _title = '';

  @override
  Widget build(BuildContext context) {
    var content = Stack(
      children: [
        WebViewWidget(
          controller: _controller,
        ),
        if (isLoading == true)
          Positioned.fill(
              child: Container(
            color: Colors.white,
            child: LoadingWidget(),
          )),
        if (error != null)
          Positioned.fill(
              child: Container(
            color: Colors.white,
            // child: Center(
            //   child: ViewStateErrorWidget(onPressed: ClickUtils.debounce(
            //     () {
            //       if (mounted) {
            //         error = null;
            //         isLoading = true;
            //         _controller?.loadUrl(widget.url);
            //         // _controller?.reload();
            //       }
            //     },
            //   )),
            // ),
            child: TextButton(
              child: ViewStateEmptyWidget(
                message: error != null ? "$error" : null,
              ),
              onPressed: ClickUtils.debounce(() async {
                // _loadingGetData();
                // _controller?.loadUrl(widget.url);
                if (mounted) {
                  setState(() {
                    isLoading = true;
                    error = null;
                  });
                  if (Platform.isIOS) {
                    _controller.loadHtmlString(widget.url);
                  } else {
                    _controller.reload();
                  }
                }

                DLog('casdvds');
              }),
            ),
          )),
      ],
    );
    return Scaffold(
      appBar: AppBar(
        titleSpacing: 0.0,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: ClickUtils.debounce(() => {_back()}),
            ),
            IconButton(
              icon: Icon(Icons.close),
              onPressed: ClickUtils.debounce(() => {_closePage()}),
            ),
            Expanded(
                child: Visibility(
              visible: error == null && isLoading == false,
              child: Center(child: Text('$_title')),
            )),
            Container(width: 96, height: 40),
          ],
        ),
        automaticallyImplyLeading: false,
        centerTitle: true,
      ),
      body: content,
    );
  }
}
